// ***** Remove bad characters from input strings ************************** //
function removeChar(str) {
	var newString = str;
	charToRemove = /"/g;	
		newString = newString.replace(charToRemove,'&#34;');
	charToRemove = /'/g;	
	newString = newString.replace(charToRemove,'&#39;');
	//document.getElementById('display').value = newString;
	//document.getElementById('displayHTML').innerHTML = newString;
	return newString;
}

// ***** getSelected selects the correct drop-down menu items in an edit screen
// ***** passed the javascript variable and the select id
function getSelect(variable,selectID) {
	var selectMenu    = document.getElementById(selectID);
	var selectOptions = selectMenu.length-1;
	var a=0;
	for(a=0;a<=selectOptions;a++) {
		if (selectMenu.options[a].value == variable) {
			document.getElementById(selectID).selectedIndex = a;
		}
	}
}

// ***** Verify that an email addres is valid ******************************* //
// ***** Written by Paolo Wales (paolo@taize.fr) **************************** //

function isValidEmail(emailad) {

   var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
   var check=/@[\w\-]+\./;
   var checkend=/\.[a-zA-Z]{2,4}$/;
   if(((emailad.search(exclude) != -1) ||
       (emailad.search(check)) == -1) ||
       (emailad.search(checkend) == -1)){
      return false;
   } else {
      return true;
   }
}

// ***** Open/Close Room Inventory Tables ************************************* //
function hideTable(rID) {
	var dataTable = document.getElementById("tableBody_"+rID);
	var control   = document.getElementById("control_"+rID);
	dataTable.style.visibility = "hidden";
	dataTable.style.height     = "0px";
	control.innerHTML = '<a href="javascript:showTable('+rID+');" onClick="showTable('+rID+');"><img src="images/arrow_right.gif" border="0"></a>';
}
function showTable(rID) {
	var dataTable = document.getElementById("tableBody_"+rID);
	var control   = document.getElementById("control_"+rID);
	dataTable.style.visibility = "";
	dataTable.style.height     = "100%";
	control.innerHTML = '<a href="javascript:hideTable('+rID+');" onClick="hideTable('+rID+');"><img src="images/arrow_down.gif" border="0"></a>';
}

// ***** Open/Close Add/Edit/View Inventory Item Windows (or any other window) ******************************************* //
function openWindow(content,displayDiv,width,height,close,background,headTitle,imagePath) {		
	opacitytitle = 45;   						
	if(width == 0) {
		width = '100%';            					
	}						
				
	var winContent = content;
	document.getElementById(displayDiv).style.visibility="visible";
	
	output = '<div class="popUpWindow" style="width: '+width+';';
	if (height > 0) { output += ' height: '+height+';">'; }
	else { output += '">'; }
	if (close) {
		output += '<div style="text-align: right;"><a href="#" onClick="closeWindow(\''+displayDiv+'\'); return false;" title="Close"><img src="'+imagePath+'images/buttonCloseSmall.gif" style="border: none;" alt="Close"></a></div>';
		output += '<div style="height: 5px;"></div>';
	}
	
	output += '<div id="windowContent">'+winContent+'</div></div>';	
	
	document.getElementById(displayDiv).innerHTML = output;
	document.getElementById(displayDiv).style.marginRight = '100px';
}
function closeWindow(displayDiv) {
	document.getElementById(displayDiv).style.visibility="hidden";
	//alert(displayDiv);
}

function addItemWin(contentID,display,headTitle) {
	var outp = document.getElementById(contentID).innerHTML;
	openWindow(outp,display,'','','',headTitle,0,'');
}

// ***** Little pause function just for kicks ******************************************** //
function pausecomp(millis) {
	date = new Date();
	var curDate = null;

	do { var curDate = new Date(); }
	while(curDate-date < millis);
} 

// ***** Show Edit and Delete Buttons on Room Nodes ************************************** //
function showControls(spanID) {
	var control = document.getElementById(spanID);
	//var controlHTML =  '<a href="javascript:editPlace('+id+');" onClick="editPlace('+id+');" title="Edit This Place"><img src="images/button_editSmall.gif" border="0"></a>&nbsp;';
	//	controlHTML += '<a href="javascript:confirmDeletePlace('+id+'); return false;" onClick="confirmDeletePlace('+id+'); return false;" title="Delete This Place"><img src="images/button_deleteSmall.gif" border="0"></a>&nbsp;';
	//control.innerHTML = controlHTML;
	control.style.visibility = '';
}

function hideControls(spanID) {
	var control = document.getElementById(spanID);
	control.style.visibility = "hidden";
}	

// ***** Show/Hide Add Room/Add Place forms ******************************************** //
function hideTable(rID) {
	var dataTable = document.getElementById("tableBody_"+rID);
	var control   = document.getElementById("control_"+rID);
	dataTable.style.visibility = "hidden";
	dataTable.style.height     = "0px";
	control.innerHTML = '<a href="javascript:showTable('+rID+');" onClick="showTable('+rID+');"><img src="images/arrow_right.gif" border="0"></a>';
}
function showTable(rID) {
	var dataTable = document.getElementById("tableBody_"+rID);
	var control   = document.getElementById("control_"+rID);
	dataTable.style.visibility = "";
	dataTable.style.height     = "100%";
	control.innerHTML = '<a href="javascript:hideTable('+rID+');" onClick="hideTable('+rID+');"><img src="images/arrow_down.gif" border="0"></a>';
}

function gotoURL(urlID) {
	var url = document.getElementById(urlID).value;
	window.open(url);
}

function printInv() {
	// Get pID from select and print images from checkbox
	// and then create redirect string
	
	var pID    = document.getElementById('printInvPlace');
	var pIndex = pID.selectedIndex;
	placeID    = pID[pIndex].value;
	
	if (document.getElementById('printImages').checked) {
		var printImages = 1;	
	} else {
		var printImages = 0;
	}	 
	
	if ( (placeID == "none") || (placeID == '') ) {
		document.getElementById('printInvMessage').innerHTML = '<font color="red">Please select a location</red>';
	} else {
		// Build redirect string
		var printURL = 'itemDetailPrint.php?pID='+placeID+'&printImages='+printImages;
		window.open(printURL,'printInv');
	}
}


function changeBG1(id) {
	document.getElementById(id).className='menuLiChange1'
}
function changeBG2(id) {
	document.getElementById(id).className='menuLiChange2'
}

// ***** GET CATEGORIES (PROJECT,INVOICE,ETC.) ***** //
function getCat(module) {
	x_getCat(module,'edit',returnGetCat);
}

function returnGetCat(string) {
	// Open window and pass string	
	openWindow(string,'catDisplay',200,0,1,'','','../');
}

function addCat(textID,module) {
	var newCat = document.getElementById(textID).value;
	if (newCat != '') {
		x_addCat(newCat,module,returnAddCat);
	}
}
function returnAddCat(string) {
	var stringArray = string.split("|");
	var selectCat   = stringArray[0];
	var editCat     = stringArray[1];
	
	document.getElementById('project_main_cat').innerHTML = selectCat;
	document.getElementById('windowContent').innerHTML    = editCat;
}

function editCat(catID,module) {
	var editTD  = 'edit'+catID;
	var catText =  document.getElementById(editTD).innerHTML;
	
	document.getElementById(editTD).innerHTML = '<input type="text" id="editText'+catID+'" style="width: 171px;" value="'+catText+'" onBlur="editCat2('+catID+',\''+module+'\');">';
}

function editCat2(catID,module) {
	var editText = document.getElementById('editText'+catID).value;
	x_editCat(editText,catID,module,returnAddCat);	
}

function deleteCat(catID,module) {	
	x_deleteCat(catID,module,returnAddCat);
}

/***** CALENDAR FUNCTIONS ******/

function newMonth(month,year,size) {
	x_displayCalendar(month,year,size,returnDisplayCalendar);
}

function returnDisplayCalendar(calString) {
	document.getElementById('calContainer').innerHTML = calString;
}

function eventDisplay(date,day) {	
	x_displayEvent(date,returnDisplayEvent);	
}

function returnDisplayEvent(string) {
	document.getElementById('eventDisplayWin').style.visibility="visible";
	document.getElementById('eventDisplay').innerHTML = string;
}

/***** END CALENDAR FUNCTIONS *****/

function checkUserid() {
	var userid = document.getElementById('addUserid').value;
	x_checkUserid(userid,returnCheckUserid);
}

function clearUserid() {
	document.getElementById('addUserid').style.background = '#ffffff';
	document.getElementById('addUseridError').innerHTML = '';
	
}

function returnCheckUserid(string) {
	if (string == 'duplicate') {
		document.getElementById('addUserid').style.background = '#ffffcc';
		document.getElementById('addUseridError').innerHTML = '<font color=red>Your selected User Name is already in use. Please select another.</font>';
	}
}

function rollWindow(window,upDown) {
	var winContentID = window;
	var winRollID    = window+'Roll';
		
	if (upDown == 'up') {
		var newHTML = '<a href="#" onClick="rollWindow(\''+window+'\',\'down\'); return false;" title="Roll Down"><img src="../images/button_rollDown.gif" style="border: none;"></a>';
		document.getElementById(winContentID).style.display = 'none';
		document.getElementById(winContentID).style.height = '0px';
		document.getElementById(winRollID).innerHTML = newHTML;
	} else if (upDown == 'down') {
		var newHTML = '<a href="#" onClick="rollWindow(\''+window+'\',\'up\'); return false;" title="Roll Up"><img src="../images/button_rollUp.gif" style="border: none;"></a>';
		document.getElementById(winContentID).style.display = '';
		document.getElementById(winContentID).style.height = '100%';
		document.getElementById(winRollID).innerHTML = newHTML;
	}
}

function showText(id,text,onOff) {
	if (onOff == 'on') {
		document.getElementById(id).innerHTML = text;
	} else {
		document.getElementById(id).innerHTML = '';
	}	
}

// A cool little bg fader thingy
// Prep the fader thingy
var FadeInterval = 300;
var StartFadeAt  = 7;
var FadeSteps = new Array();
	FadeSteps[1] = "ff";
	FadeSteps[2] = "ee";
	FadeSteps[3] = "dd";
	FadeSteps[4] = "cc";
	FadeSteps[5] = "bb";
	FadeSteps[6] = "aa";
	FadeSteps[7] = "99";
function doFade(colorId, targetId) {
    if (colorId >= 1) {
		document.getElementById(targetId).style.backgroundColor = "#ffff" + FadeSteps[colorId];
		
        // If it's the last color, set it to transparent
        if (colorId==1) {
            document.getElementById(targetId).style.backgroundColor = "transparent";
		}
        colorId--;
		
        // Wait a little bit and fade another shade
        setTimeout("doFade("+colorId+",'"+targetId+"')", FadeInterval);
	}
} 

function ajaxAnim(animID) {
	document.getElementById(animID).innerHTML = '<img src="images/ajaxAnimSmall2.gif"> Working...';
	doFade(7,animID);
}

function ajaxAnimStop(animID) {
	document.getElementById(animID).innerHTML = '';
}

function closeWindow(windowID) {
	document.getElementById(windowID).style.display = 'none';
}

function divRollUpDown(element) {
	var displayStatus = $(element).style.display;
	if (displayStatus == 'none') {
		// Roll Down
		new Effect.SlideDown(element, {direction: 'top', duration: .2});
		$(element).title = 'Roll Up';
	} else {
		Effect.SlideUp(element, {direction: 'top', duration: .2});
		$(element).title = 'Roll Down';
	}	
}

function divClose(element) {
	var displayStatus = $(element).style.display;
	if (displayStatus != 'none') {
		Effect.SlideUp(element, {direction: 'top', duration: .2});
	}
}

function rowHoverControls(id,onOff,offClass) {
	var rowID     = 'row'+id;
	var controlID = 'control'+id;
	
	if (onOff == 'on') {
		$(rowID).className = 'hiLite';
		$(controlID).style.display = 'block';
	} else {
		$(rowID).className  = offClass;
		$(controlID).style.display = 'none';
	}	
}

function checkInputToClear(elementID,text) {
	if (elementID.value == text) {
		elementID.value = '';
	}
}

function confirmDelete(itemID,deleteWhat) {
	if (deleteWhat == 'resource') {
		var OK = confirm("Are you sure you want to delete this Link?");
		if (OK == true) {
			x_deleteResource(itemID,returnConfirmDelete);
		}
	} else if (deleteWhat == 'selectedTopicLink') {
		var OK = confirm("Are you sure you want to delete this Selected Topic Link?");
		if (OK == true) {
			linkDelete(itemID);
		}
	} else if (deleteWhat == 'file') {
		var OK = confirm("Are you sure you want to delete this File?");
		if (OK == true) {
			x_deleteFile(itemID,filesDeleteObj.returnDeleteFile);			
		}
	} else if (deleteWhat == 'format') {
		var OK = confirm("Are you sure you want to delete this Format and all associated Links?");
		if (OK == true) {
			x_deleteFormat(itemID,returnDeleteFormat);			
		}
	} else if (deleteWhat == 'event') {
		var OK = confirm("Are you sure you want to delete this Event or News Item?");
		if (OK == true) {
			x_deleteEvent(itemID,returnDeleteEvent);			
		}
	} else if (deleteWhat == 'product') {
		var OK = confirm("Are you sure you want to delete this Product?");
		if (OK == true) {
			x_deleteProduct(itemID,returnDeleteProduct);			
		}
	} else if (deleteWhat == 'user') {
		var OK = confirm("Are you sure you want to delete this Administrator?");
		if (OK == true) {
			x_deleteUser(itemID,returnDeleteUser);			
		}
	}		
}

function updateStatus(message,status) {
	if (status == 'error') {
		$('statusDiv').innerHTML = '<div id="statusDivInner" class="errorMessage">'+message+'</div>';
	} else if (status == 'success') {
		$('statusDiv').innerHTML = '<div id="statusDivInner" class="successMessage">'+message+'</div>';
	}	
	Effect.Fade('statusDivInner', {delay: 1, duration: 3});
	//$('statusDiv').innerHTML = '';
}

// ***** TOOL TIP JAVASCRIPT **********************************************************
//browser detection
var agt=navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);

var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
            && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
            && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_nav4 = (is_nav && (is_major == 4));
var is_nav6 = (is_nav && (is_major == 5));
var is_nav6up = (is_nav && (is_major >= 5));
var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

//tooltip Position
var offsetX = 8;
var offsetY = -62;
var opacity = 100;
var toolTipSTYLE;

function initToolTips(){
  if(document.getElementById){
          toolTipSTYLE = document.getElementById("toolTipLayer").style;
  }
  if(is_ie || is_nav6up)
  {
    toolTipSTYLE.visibility = "visible";
    toolTipSTYLE.display = "none";
    document.onmousemove = moveToMousePos;
  }
}
function moveToMousePos(e)
{
  if(!is_ie){
    x = e.pageX;
    y = e.pageY;
  }else{
    x = event.x + document.body.scrollLeft;
    y = event.y + document.body.scrollTop;
  }

  toolTipSTYLE.left = x + offsetX+'px';
  toolTipSTYLE.top = y + offsetY+'px';
  return true;
}


function toolTip(msg, type) {
  if(toolTip.arguments.length < 1) // if no arguments are passed then hide the tootip
  {
    if(is_nav4)
        toolTipSTYLE.visibility = "hidden";
    else
        toolTipSTYLE.display = "none";
  }
  else // show
  {
  	// Delay
  	//pause(750);
    
    if (type == 'baloon') {
    	var content = '<div class="toolTipBaloon">'+msg+'</div>';
    } else {
		var content = '<div class="toolTipBox" style="margin-top: 30px;"><p>'+msg+'</p></div>';
	}
    
   if(is_nav4)
    {
      toolTipSTYLE.document.write(content);
      toolTipSTYLE.document.close();
      toolTipSTYLE.visibility = "visible";
    }

    else if(is_ie || is_nav6up)
    {
      document.getElementById("toolTipLayer").innerHTML = content;
      toolTipSTYLE.display='block'
    }
  }
}

function show(arg1,arg2){
        toolTip(s)
}
// ***** END TOOL TOP JAVASCRIPT ************************************************

// ***** TREE JAVASCRIPT ********************************************************
function createResourceTree() {	
	var Tree = Ext.tree;
    
    var tree = new Tree.TreePanel('resourceTree', {
        animate:true, 
        loader: new Tree.TreeLoader({
            dataUrl:'includes/sajax/sajaxResources.php?createTree=1'
        }),
        enableDD:true,
        containerScroll: true
    });

    // set the root node
    var root = new Tree.AsyncTreeNode({
        text: 'All Resources',
        draggable:false,
        id:'source'
    });
    tree.setRootNode(root);
    var treeLoader = tree.loader;
    treeLoader.on("beforeload", function(treeLoader, node) {
        treeLoader.baseParams.level = node.attributes.level;
    }, this);

	var treeNodeClick = function(node) {
		var nodeID = node.attributes.id;
		var level  = node.attributes.level;
		
		if (level == 3) {
			x_getResources(nodeID,level,returnGetResources);
		} else {
			// Don't do anything here yet.
		}
	}
	
	tree.on('click', treeNodeClick, this, true);
	
	// render the tree
    tree.render();
    root.expand();
}    
// ***** END TREE JAVASCRIPT ****************************************************

// ***** COOKIE FUNCTIONS *******************************************************

// Set a cookie of name = value with path and domain
function cookieSet( name,value,expireDays,path,domain,secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	if (!path) { path = '/'; }
	if (!domain) { domain = 'creativeprooffice.com'; }
	if (!expireDays) {
		var expireDays = 1;
	}	
		
	var expires = expireDays * 1000 * 60 * 60 * 24;
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

// Get the cookie, if it exists
function cookieGet(name) {	
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

// Delete cookie
function cookieDelete( name, path, domain ) {
	if (!path) { path = '/'; }
	if (!domain) { domain = 'creativeprooffice.com'; }
	if ( cookieGet( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// ***** END COOKIE FUNCTIONS *****************************************************

function exportResources() {
	if ($('exportCurrentView').checked == true) {
		var pathID = $('pathID').value;
		x_exportResources('csv',pathID,returnExportResources);
	} else if ($('exportAll').checked == true) {
		x_exportResources('csv',0,returnExportResources);
	} else {
		x_exportResources('csv',0,returnExportResources);	
	}
	/*
	 * Clear download link div from any previous content
	 */
	$('exportDownload').innerHTML = '';
	showAJAXSpinner('spinnerDivDownload');
}

function returnExportResources(string) {
	hideAJAXSpinner('spinnerDivDownload');
	$('exportDownload').innerHTML = '<a href="download.php?file='+string+'" class="buttonDownloadFile">Download file</a>';
}

function toggleCheck(formID) {
	var checkBox = $(formID).checked;
	if (!checkBox) { $(formID).checked = true; }
	else { $(formID).checked = false; }
}

function search() {
	var searchTerm = $('searchTerm').value;
	if ( (searchTerm != '') && (searchTerm != 'Search for...') ) {
		x_search(searchTerm,returnSearch);
	} else {
		$('searchError').innerHTML = 'You must enter a search term.';
	}
}

function returnSearch(searchResults) {
	var stringArray = searchResults.split('|');
	var searchResults = stringArray[0];
	var searchTerm    = stringArray[1];
	var noResults     = stringArray[2];
	
	if (noResults == 1) {
		var resultText = 'Result';
	} else if ( (noResults>1) || (noResults == 0) ) {
		var resultText = 'Results';
	} 
	// Set search panel title results
	//var panelTitle = panel1.getTitle();
	panel1.setTitle('Search Results ('+noResults+')');
	
	// Switch to search results panel
	Example.toggleContent(1,'','');
	$('resourceSearchList').innerHTML = '<h1>Search Results for '+searchTerm+' ('+noResults+' '+resultText+')</h1>'+searchResults;
}

function showAJAXSpinner(renderDiv) {
	$(renderDiv).innerHTML = '<img src="images/ajaxAnimSmall2.gif" />';
}

function hideAJAXSpinner(renderDiv) {
	$(renderDiv).innerHTML = '';
}

